<template>
	<view>
		<view class="bgImg" :style="{ backgroundImage : 'url(' + songDetail.al.picUrl + ')' }"></view>
		<musicHead :title="songDetail.name" :showIcon="true" textHeadColor="white" className="detail"></musicHead>
		<view class="container" v-show="isLoading">
			<scroll-view scroll-y="true">
				<view class="detail">
					<view class="logo">
						<image src="../../static/网易云.jpg"></image>
						<view>网易云音乐</view>
					</view>
					<view class="main">
						<view class="img">
							<image src="../../static/机械臂.png"></image>
							<image src="../../static/黑胶.png" :class="{rotate:showPlayIcon,pause:!showPlayIcon}"></image>
							<image :src="songDetail.al.picUrl" :class="{rotate:showPlayIcon,pause:!showPlayIcon}"></image>
							<view class="iconfont icon-bofang play" v-if="!showPlayIcon" @click="changePlay"></view>
							<view class="iconfont icon-zanting pause" v-if="showPlayIcon" @click="changePlay"></view>
						</view>
						<!-- 歌词 -->
						<view class="text">
							<view v-for="item,index in formatLyric" :key="index" 
							class="app-text-ellipsis"
							:class="{active:index==lyricIndex}" 
							:style="{ transform : 'translateY(' + - (lyricIndex-1)*80 + 'rpx)' }"
							>{{item.lyric}}</view>
							<!-- <bing-lyric :lyrics="newFormatLyric" :curTime="lyricIndex"></bing-lyric> -->
						</view>
					</view>
					<button open-type="share">分享给微信好友</button>
					<!-- 推荐歌曲 -->
					<view class="commend">
						<view class="commend-title">
							<view>喜欢这首歌的人也在听</view>
							<view><text class="iconfont icon-bofang"></text>一键收听</view>
						</view>
						<!-- 推荐歌曲列表 -->
						<view class="song-list" v-for="item in simiSong" :key="item.id" @click="changeMusic(item.id)">
							<view class="number">
								<image :src="item.album.blurPicUrl"></image>
							</view>
							<view class="content">
								<view class="special app-text-ellipsis">{{item.name}}</view>
								<view class="little app-text-ellipsis">
									<text>{{item.artists[0].name}} - {{item.name}}</text>
								</view>
							</view>
							<view class="iconfont icon-bofang play"></view>
						</view>
					</view>
					<!-- 评论区 -->
					<view class="comments">
						<view class="title">精彩评论</view>
						<view v-for="item in commentMusic" :key="item.commentId">
							<view class="content">
								<view class="left">
									<view class="headshot"><image :src="item.user.avatarUrl"></image></view>
									<view class="info">
										<view class="name">{{item.user.nickname}}</view>
										<view class="time">{{item.time | formatTime}}</view>
									</view>
								</view>
								<view class="right">
									{{item.likedCount}}<text class="iconfont icon-icon"></text>
								</view>
							</view>
							<!-- 评论内容 -->
							<view class="text">{{item.content}}</view>
							<view class="line"></view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import {songDetail,simiSong,songUrl,commentMusic,lyric} from '../../common/api.js'
	// 歌词插件，没有用到，或者说不会用
	// import bingLyric from '../../components/bing-lyric/bing-lyric.vue'
	export default {
		data() {
			return {
				songDetail:{
					al:{
						picUrl:''
					},
					ar:[
						{
							name:''
						}
					],
					name:''
				},
				simiSong:[],
				songUrl:'',
				// 格式化后的歌词
				formatLyric:[],
				newFormatLyric:[],
				// 控制歌词的选中状态
				lyricIndex:0,
				// 热评
				commentMusic:[],
				// 控制播放与暂停icon的切换
				showPlayIcon:true,
				// 控制loading效果，当数据没有获取到时，加载loading
				isLoading:false
			}
		},
		onUnload(){
			// 退出组件时清除定时器（小返回对应）
			clearInterval(this.timer)
			// H5退出时销毁H5音乐播放对象
			// #ifdef H5
				this.bgAudioManager.destroy()
			// #endif
		},
		onLoad({id}) {
			// console.log(id,'************************')
			// 通过当前歌曲的id，通知vuex计算并保存下一首歌曲的id
			this.$store.commit('NEXT_ID',id)
			this.initMusic(id)
		},
		onHide(){
			// 页面隐藏时清除定时器（大返回对应页面隐藏）
			clearInterval(this.timer)
			// H5退出时销毁H5音乐播放对象
			// #ifdef H5
				this.bgAudioManager.destroy()
			// #endif
		},
		// onShow(){
		// 	// #ifdef H5
		// 		// 当H5页面再次展示的时候，继续音乐（没必要设置）
		// 		this.startPlayMusic()
		// 	// #endif
		// },
		methods:{
			initMusic(id){
				// 加载loading
				uni.showLoading({
					title:'加载中...'
				})
				// 获取歌曲详情----背景图、名字
				songDetail(id).then(res=>{
					// console.log(res,'歌曲详情')
					this.songDetail = res.data.songs[0] 
				})
				// 获取相似歌曲推荐
				simiSong(id).then(res=>{
					// console.log(res,'相似歌曲推荐')
					this.simiSong = res.data.songs
				})
				// 获取歌曲mp3
				songUrl(id).then(res=>{
					// console.log(res,'歌曲mp3')
					this.songUrl = res.data.data[0].url
					// 开启音乐播放
					this.startPlayMusic()
				})
				// 获取歌词
				lyric(id).then(res=>{
					// 格式化歌词
					let lyric = res.data.lrc.lyric
					let regex = /\[([^\]]+)\]([^\[]+)/g;
					const result = []
					lyric.replace(regex,($0,$1,$2)=>{
						result.push( {"time":this.formatLyricTime($1) , "lyric":$2} )
					})
					// // 将格式化后的结果保存
					this.formatLyric = result
				})
				// 获取评论
				commentMusic(id).then(res=>{
					// console.log(res,'评论')
					this.commentMusic = res.data.hotComments
				})
				// 加载完成
				this.isLoading = true
				uni.hideLoading()
			},
			// 格式化歌词时间
			formatLyricTime(value){
				const arr = value.split(":")
				// 注意 tofixed需要一个数字，并且会将结果转为字符串
				return arr[0]*60 + ((arr[1]*1).toFixed(1)*1)
			},
			// 开启音乐播放
			startPlayMusic(){
				// #ifdef MP-WEIXIN
					this.bgAudioManager = uni.getBackgroundAudioManager();
					this.bgAudioManager.title = this.songDetail.name;
					this.bgAudioManager.singer = this.songDetail.ar[0].name
					this.bgAudioManager.coverImgUrl = this.songDetail.al.picUrl;
				// #endif
				
				// #ifdef H5
				    // 当播放一首歌时（没有暂停），如果直接返回再去播放另外一首歌，会导致同时播放
					// 两首歌，暂时解决：当有歌曲正在播放的时候，不能播放其他歌曲
					if(!this.bgAudioManager){
						this.bgAudioManager = uni.createInnerAudioContext();
					}
					this.bgAudioManager.autoplay = true;
				// #endif
				// 当歌曲url没有时
				if(this.songUrl){
					this.bgAudioManager.src = this.songUrl || '';
					// 开启匹配歌词
					this.matchLyric()
					// 点击微信自带的暂停与播放时，使图片旋转与incon切换对应变化
					this.bgAudioManager.onPlay(()=>{
						this.showPlayIcon = true
						// 开启匹配歌词
						this.matchLyric()
					})
				}else{
					uni.showToast({
						title:'歌曲无版权',
						icon:'none'
					})
					// 暂停图片旋转
					this.showPlayIcon = false
				}
				
				// 歌曲暂停
				this.bgAudioManager.onPause(()=>{
					this.showPlayIcon = false
					// 暂停时清除定时器
					clearInterval(this.timer)
				})
				// 当播放停止时，切换下一首歌曲
				this.bgAudioManager.onEnded(()=>{
					this.initMusic(this.$store.state.nextId)
				})
			},
			// 改变播放icon显示及暂停与播放
			changePlay(){
				// 如果歌曲url存在，则可以切换
				if(this.songUrl){
					if(this.showPlayIcon){
						this.bgAudioManager.pause()
						// 暂停时清除定时器
						clearInterval(this.timer)
					}else{
						this.bgAudioManager.play()
					}
					this.showPlayIcon = !this.showPlayIcon
				}else{
					uni.showToast({
						title:'歌曲无版权',
						icon:'none'
					})
				}
				
			},
			// 音乐播放时，歌词的对应位置
			matchLyric(){
				clearInterval(this.timer)
				const forLy = this.formatLyric;
				// let curTime = this.bgAudioManager.currentTime  歌曲时间需要动态获取
				this.timer = setInterval(()=>{
					for(let i = 0; i < forLy.length; i++){
						// 如果到达歌词的最后一项，解决i+1溢出的报错
						if(this.bgAudioManager.currentTime > forLy[forLy.length-1]){
							this.lyricIndex = forLy.length - 1;
							break;
						}
						// 当前音乐时间处于某歌词时间之间时，将当前歌词下标保存更新
						if(this.bgAudioManager.currentTime > forLy[i].time && this.bgAudioManager.currentTime < forLy[i+1].time){
							this.lyricIndex = i
						}
					}
					// console.log(this.lyricIndex)
				},500)
			},
			// 切换推荐音乐
			changeMusic(id){
				// Object.assign(this._data, this.$options.data())
				// 重新初始化
				this.initMusic(id)
			}
		}
	}
</script>

<style lang="scss" scoped>
	
	.detail {
		position: relative;
		.logo {
			position: absolute;
			top: 0;
			left: 20rpx;
			display: flex;
			align-items: center;
			color: #fff;
			font-size: 26rpx;

			image {
				width: 38rpx;
				height: 38rpx;
				border-radius: 50%;
				margin-right: 12rpx;
			}
		}

		.main {
			.img {
				.rotate{
					animation: rotate linear infinite 7s;
					animation-play-state:running;
					-webkit-animation-play-state:running; /* Safari 和 Chrome */
					@keyframes rotate{
						0%{
							transform: rotateZ(0deg);
						}
						100%{
							transform: rotateZ(360deg);
						}
					}
				}
				.pause{
					animation: rotate linear infinite 7s;
					// 停止时、图片保持停止时的状态
					animation-play-state:paused;
					-webkit-animation-play-state:paused; /* Safari 和 Chrome */
					@keyframes rotate{
						0%{
							transform: rotateZ(0deg);
						}
						100%{
							transform: rotateZ(360deg);
						}
					}
				}
				image:nth-child(1) {
					height: 328rpx;
					width: 200rpx;
					position: absolute;
					top: 0;
					left: 356rpx;
					z-index: 3;
				}
				image:nth-child(2) {
					width: 578rpx;
					height: 578rpx;
					position: relative;
					top: 190rpx;
					left: 88rpx;
					z-index: 2;
					filter: brightness(.7);
				}
				image:nth-child(3){
					width: 370rpx;
					height: 370rpx;
					position: absolute;
					top: 300rpx;
					left: 190rpx;
					z-index: 1;
					border-radius: 50%;
				}
				.play,.pause{
					color: #fff;
					font-size: 104rpx;
					position: absolute;
					width: 96rpx;
					height: 96rpx;
					top: 426rpx;
					left: 324rpx;
					z-index: 3;
				}
			}

			.text {
				margin-top: 200rpx;
				text-align: center;
				color: #acacac;
				height: 240rpx;
				overflow: hidden;
				font-size: 28rpx;
				view{
					line-height: 80rpx;
					height: 80rpx;
					// 歌词移动过渡
					transition: .5s;
					padding: 0 20rpx;
					// 某些歌词一行放不下，隐藏一部分
					// overflow: hidden;
					// text-overflow: ellipsis;
					// white-space: nowrap;
				}
				.active{
					color: #fff;
				}
			}
		}
		button {
			margin-top: 70rpx;
			width: 332rpx;
			height: 70rpx;
			border-radius: 42rpx;
			font-size: 26rpx;
			line-height: 70rpx;
			color: #fff;
			background: transparent;
			border: 2rpx solid rgba(255, 255, 255, .3);
		}

		.commend {
			padding: 58rpx 46rpx 46rpx;
			color: #fff;

			.commend-title {
				display: flex;
				justify-content: space-between;

				view:nth-child(1) {
					font-size: 34rpx;
					margin-top: 6rpx;
				}

				view:nth-child(2) {
					width: 172rpx;
					height: 60rpx;
					border-radius: 30rpx;
					border: 2rpx solid rgba(255, 255, 255, .1);
					line-height: 60rpx;
					text-align: center;
					font-size: 26rpx;

					text {
						font-size: 26rpx;
						margin-right: 6rpx;
					}
				}
			}

			.song-list {
				height: 122rpx;
				display: flex;
				justify-content: space-between;
				color: #c3c3c3;
				.number {
					width: 84rpx;
					height: 84rpx;
					text-align: center;
					font-size: 32rpx;
					image{
						width: 100%;
						height: 100%;
						margin-top: 20rpx;
						border-radius: 10rpx;
					}
				}
				.content {
					width: 400rpx;
					margin-left: -80rpx;
					.special {
						color: #fff;
						font-size: 30rpx;
						margin: 20rpx 0 10rpx;
						// 全局定义
						// overflow: hidden;
						// text-overflow: ellipsis;
						// white-space: nowrap;
					}

					.little {
						font-size: 24rpx;
						// overflow: hidden;
						// text-overflow: ellipsis;
						// white-space: nowrap;
						color: #acacac;
					}
				}

				.play {
					line-height: 120rpx;
					font-size: 52rpx;
				}
			}
		}
		.comments{
			padding: 0 46rpx;
			color: #fff;
			font-size: 32rpx;
			
			.title{
				margin-bottom: 42rpx;
			}
			.content{
				display: flex;
				justify-content: space-between;
				.left{
					width: 532rpx;
					height: 66rpx;
					display: flex;
					justify-content: space-between;
					.headshot{
						width: 66rpx;
						height: 66rpx;
						image{
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}
					.info{
						width: 442rpx;
						height: 62rpx;
						.name{
							font-size: 24rpx;
							color: #acacac;
						}
						.time{
							font-size: 20rpx;
							color: #767675;
						}
					}
				}
				.right{
					width: 126rpx;
					height: 48rpx;
					font-size: 24rpx;
					color: #767675;
					text{
						margin-left: 10rpx;
					}
				}
			}
			.text{
				margin-left: 88rpx;
				font-size: 26rpx;
				width: 530rpx;
				// padding-bottom: 40rpx;
				// border-bottom: 2rpx solid #767675;
			}
			.line{
				width: 536rpx;
				height: 2rpx;
				margin: 30rpx 0 30rpx 90rpx;
				border-bottom: 2rpx solid #767675;
			}
		}
	}
</style>
